﻿using Core.AdminUI.V2.Controllers.Base;
using Core.FrameWork.Commons.ApiResult;
using Core.FrameWork.Commons.Storage;
using Core.FrameWork.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace Core.AdminUI.V2.Controllers
{
    public class UploadController : BaseController
    {
        public UploadController(AdminContext db) : base(db)
        {
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="type">Face = 1,Voice = 2,Image = 3,Video = 4, file = 5, </param>
        /// <param name="file">文件二进制流 </param>
        /// <returns></returns>
        [HttpPost]
        public async Task<CommonResult<UploadResult>> Upload([FromForm] IFormFile file, [FromForm] UploadFileType type = UploadFileType.Image)
        {
            UploadResult result = new UploadResult();
            var files = Request.Form.Files;
            if (files.Count > 0)
            {
                var FileFile = files[0];
                if (FileFile != null && FileFile.FileName != "")
                {
                    string NameStr = Guid.NewGuid().ToString();
                    string newFileName = string.Format("{0}{1}", NameStr, GetFileExtension(FileFile.FileName));
                    string fileurl = string.Empty;
                    var bytes = StreamToBytes(FileFile.OpenReadStream());
                    fileurl = await UploadHelp.Execute(bytes, newFileName, type);
                    result.FileName = newFileName;
                    result.FileUrl = fileurl;

                    return ApiRespHelp.GetApiData(result);

                }
            }
            return ApiRespHelp.getError<UploadResult>(-100, "上传失败");
        }

        ///// <summary>
        ///// 分片上传
        ///// </summary>
        ///// <param name="file"></param>
        ///// <param name="type"></param>
        ///// <returns></returns>
        //public RespResult<UploadResult> UploadBlack([FromForm] IFormFile file, string fileName, [FromQuery] UploadFileType type = UploadFileType.Image)
        //{
        //    UploadResult result = new UploadResult();
        //    var files = Request.Form.Files;
        //    if (files.Count > 0)
        //    {
        //        var FileFile = files[0];
        //        if (FileFile != null && FileFile.FileName != "")
        //        {
        //            var bytes = StreamToBytes(FileFile.OpenReadStream());
        //            var blackId = UploadHelp.ExecuteBlack(bytes, fileName, type);
        //            result.FileName = fileName;
        //            result.FileUrl = blackId;

        //            return ApiRespHelp.getApiData(result);
        //        }
        //    }
        //    return ApiRespHelp.getError<UploadResult>(-100, "上传失败");
        //}
        /// <summary>
        /// 分片上传
        /// </summary>
        /// <param name="file"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<CommonResult<UploadResult>> UploadBlack([FromForm] IFormFile file, string fileName, [FromQuery] UploadFileType type = UploadFileType.Image)
        {
            UploadResult result = new UploadResult();
            var files = Request.Form.Files;

            string t = Request.Query["t"];
            if (!string.IsNullOrWhiteSpace(t))
            {
                type = (UploadFileType)int.Parse(t);
            }

            if (files.Count > 0)
            {
                var FileFile = files[0];
                if (FileFile != null && FileFile.FileName != "")
                {
                    var bytes = StreamToBytes(FileFile.OpenReadStream());
                    var blackId = await UploadHelp.ExecuteBlack(bytes, fileName, type, UploadFunEnum.LocationBlack);
                    result.FileName = fileName;
                    result.FileUrl = blackId;

                    return ApiRespHelp.GetApiData(result);
                }
            }
            return ApiRespHelp.getError<UploadResult>(-100, "上传失败");
        }
        /// <summary>
        /// 分片内容执行合并
        /// </summary>
        /// <param name="blacks"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<CommonResult<UploadResult>> MergeBlack([FromForm] List<string> blacks, string fileName, [FromQuery] UploadFileType type = UploadFileType.Image)
        {
            var result = new UploadResult();
            var fileExp = Path.GetExtension(fileName);
            var newFileName = $"{Guid.NewGuid()}{fileExp}";
            var fileUrl = await UploadHelp.MergeBlack(fileName, newFileName, blacks, type);
            result.FileName = fileName;
            result.FileUrl = fileUrl;
            return ApiRespHelp.GetApiData(result);
        }

        /// <summary>
        /// 文件结果
        /// </summary>
        public class UploadResult
        {
            /// <summary>
            /// 文件名
            /// </summary>
            public string FileName { get; set; }
            /// <summary>
            /// 文件地址
            /// </summary>
            public string FileUrl { get; set; }

        }

        protected string GetFileExtension(string fileName)
        {
            if (fileName.IndexOf(".") > 0)
            {
                return fileName.Substring(fileName.LastIndexOf("."));
            }
            return "";
        }


        protected byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }




    }

}